<?php

namespace addons\cloud_market\utils;

use addons\cloud_market\model\CloudMarketSms;
use Overtrue\EasySms\EasySms;
use think\facade\Cache;

class Sms
{
    /**
     * 短信配置
     * @var array
     */
    protected static $config = [
        // HTTP 请求的超时时间（秒）
        'timeout' => 5.0,
        // 默认发送配置
        'default' => [
            // 网关调用策略，默认：顺序调用
            'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
            // 默认可用的发送网关
            'gateways' => [
                'aliyun',
            ],
        ],
        // 可用的网关配置
        'gateways' => [
            'aliyun' => [
                'access_key_id' => 'LTAI5tNnJapat33r7S4x1rC3',
                'access_key_secret' => 'LsLaA1MseRfZ9ZoBCCEy1qaiBe2YVt',
                'sign_name' => '多客怪兽',
            ],
        ],
    ];

    /**
     * 发送短信验证码
     * @param string $mobile 手机号
     * @param string $code 验证码(如果为null则自动生成)
     * @param string $event 事件类型
     * @return bool
     */
    public static function send($mobile, $code = null, $event = 'register')
    {
        try {
            // 生成验证码
            if ($code === null) {
                $code = mt_rand(1000, 9999);
            }

            // 初始化短信客户端
            $easySms = new EasySms(self::$config);

            // 发送短信
            $result = $easySms->send($mobile, [
                'template' => 'SMS_226995092',
                'data' => [
                    'code' => $code
                ],
            ]);
            if ($result) {
                // 保存到数据库
                $smsModel = new CloudMarketSms();
                $smsModel->save([
                    'event' => $event,
                    'phone' => $mobile,
                    'code' => $code,
                    'ip' => request()->ip(),
                    'times' => 1,
                    'status' => 0,  // 0表示未使用
                    'create_time' => time(),
                ]);

                return true;
            }

            return false;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取最近的短信记录
     * @param string $mobile 手机号
     * @param string $event 事件类型
     * @return array|null
     */
    public static function get($mobile, $event = 'register')
    {
        $smsModel = new CloudMarketSms();
        $record = $smsModel->where([
            'phone' => $mobile,
            'event' => $event
        ])->order('create_time', 'desc')->find();

        if ($record) {
            return [
                'create_time' => $record->create_time,
                'code' => $record->code,
                'times' => $record->times,
                'status' => $record->status,
            ];
        }

        return null;
    }

    /**
     * 验证短信验证码
     * @param string $mobile 手机号
     * @param string $code 验证码
     * @param string $event 事件类型
     * @return bool
     */
    public static function check($mobile, $code, $event = 'register')
    {
        $smsModel = new CloudMarketSms();
        $record = $smsModel->where([
            'phone' => $mobile,
            'event' => $event,
            'code' => $code,
            'status' => 0  // 只查找未使用的验证码
        ])->order('create_time', 'desc')->find();

        if ($record) {
            // 检查验证码是否过期 (5分钟内有效)
            if (time() - strtotime($record->create_time) <= 300) {
                // 验证成功后标记为已使用
                $record->status = 1;
                $record->save();
                return true;
            }
        }
        return false;
    }

    /**
     * 清理过期的短信记录
     */
    public static function cleanExpired()
    {
        $smsModel = new CloudMarketSms();
        // 删除10分钟前的记录
        $smsModel->where('create_time', '<', time() - 600)->delete();
    }
}
